<?php

abstract class Worker
{
    protected $id;
    protected $name;
    protected $workers;
    protected $config;
    /**
     * @var HTTP
     */
    protected $http;

    public function __construct($name = null)
    {
        $this->name = $name;
        $this->config = Container::get('config');
        $this->http = new HTTP();
    }


    public function actionStatus()
    {
        return "{$this->name} #{$this->id}/{$this->workers} fine";
    }

    public function publishMethod($name, $method)
    {
        Container::get('gearman')->addFunction($this->name . '.' . $name, array($this, $method));
    }

    public function run()
    {
//        $this->out("started");
        $gearman = Container::get('gearman');
        while ($gearman->work()) {
//            $this->out("Waiting for job...");
            if ($gearman->returnCode() != GEARMAN_SUCCESS) {
                $this->out("Gearman return code: " . $gearman->returnCode());
                break;
            }
        }
    }

    public function out($message)
    {
        echo "{$this->name}#{$this->id}: " . $message . PHP_EOL;
    }


    public function gedDaysBeforeNextCheck($lastGoodResultAt)
    {
        $goodResultAt = $lastGoodResultAt && strtotime($lastGoodResultAt) ?: time();
        $lastCheckTime = ($goodResultAt - time()) / (3600 * 24);
        if ($lastCheckTime > 180) {
            $checkAfterDays = 90;
        } else if ($lastCheckTime > 21) {
            $checkAfterDays = 30;
        } else {
            $checkAfterDays = 7;
        }

        return $checkAfterDays;
    }
}
